import type { ChatCompletionChunk } from "openai/resources";

export const createStopMessage = (content = "") => {
  return {
    choices: [{ delta: { content }, finish_reason: "stop", index: 0 }],
    id: "",
    created: 0,
    model: "",
    object: "chat.completion.chunk",
  } as ExtendedChatCompletionChunk;
};
export const createErrorMessage = (content = "") => {
  return {
    choices: [{ delta: { content }, finish_reason: "error", index: 0 }],
    id: "",
    created: 0,
    model: "",
    object: "chat.completion.chunk",
  } as ExtendedChatCompletionChunk;
};

export const useStream = async (
  readable: ReadableStream<Uint8Array>,
  handler: (decoded: ExtendedChatCompletionChunk) => any
) => {
  const stream = readable.getReader();
  while (true) {
    const { done, value } = await stream.read();
    if (done) {
      handler(createStopMessage());
      break;
    }
    const decodedArray = new TextDecoder().decode(value).split("data: ");
    decodedArray.forEach(async (decoded) => {
      try {
        const data = JSON.parse(decoded);
        handler(data as ExtendedChatCompletionChunk);
      } catch {}
    });
  }
};
